import { authorizedList } from '@/api/authorized';
import {
  productWoocAdd,
  productWoocRead,
  productWoocEdit,
  productVariantList,
  productCategoryList,
  productCategoryAdd,
  productTagList,
  productTagAdd,
  vendorList,
  vendorAdd
} from '@/api/product';
import UE from '@/components/Ueditor/ueditor.vue';
import AllTag from '../components/allTag';
import MultipleCategory from '../components/multipleCategory';
import AllVendor from '../components/allVendor';
import AllVariant from '../components/allVariant';
import ThumbnailDialog from '../components/thumbnailDialog';
import UploadVariant from '../components/uploadVariantWooc';
import BatchModify from '../components/batchModify';
import ProviewImg from '@/components/Proview/proviewImg';
import { flatten } from '@/utils/dataFormat';
import {
  formRules,
  watchSpecifications,
  batchOption,
  toggleCheck,
  changeVariantSku
} from './commonDet';
export default {
  components: {
    UE,
    ThumbnailDialog,
    AllTag,
    MultipleCategory,
    AllVendor,
    AllVariant,
    UploadVariant,
    BatchModify,
    ProviewImg
  },
  data() {
    return {
      loading: true,
      pageType: 'Add',
      storeId: null, // 店铺ID
      productId: null, // 商品ID
      storeList: [],
      categoryOptions: [], // 分类列表
      categoryProp: {
        multiple: true,
        checkStrictly: true,
        emitPath: false,
        label: 'name',
        value: 'id',
        children: 'seconds'
      },
      category: [],
      tagOptions: [],
      vendorOptions: [],
      formData: {
        isManageInventory: 0,
        inventoryStatus: 0,
        taxStatus: 1,
        taxClass: 'Standard',
        type: 0,
        isVirtual: 0,
        shippingClassId: 0,
        productTagIds: [],
        isDimensions: 0,
        // 生成的变种信息
        specificationData: []
      },
      rules: formRules(this.checkStr, this),
      ue: 'ue',
      defaultMsg: '',
      thumbnailShow: false,
      images: [],
      proviewUrl: '', // 预览图片Url
      timeChange: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 选择时间范围
        }
      },
      viewTags: false,
      viewCategory: false,
      viewVendor: false,
      viewVariant: false,
      chargeTax: '',
      allListLeaf: [], // 所有规格叶子节点，比对规格ID使用
      specifications: [
        // 规格信息(树结构)
        {
          parent: '',
          son: []
        }
      ],
      firstRandom: true, // 首次渲染变种信息
      cloneSpecificationData: [], // 商品中保存的规格信息，新加规格信息若在其中存在，使用其数据
      specList: [],
      selectOptions: [], // 当前选取规格值得子选项
      batchVisible: false,
      writeLabel: '', // 批量写入变种信息的具体参数
      batchRows: [],
      variantDialogVisible: false,
      batchOptions: batchOption
    };
  },
  watch: {
    specifications: {
      // 监听规格信息变化，生成变种信息
      handler(newVal) {
        watchSpecifications(newVal, this, 'wooc');
      },
      deep: true
    }
  },
  mounted() {
    this.$set(this.formData, 'rules', this.rules);
    if (this.$route.params.storeId === undefined) {
      // 添加
      this.pageType = 'Add';
      this.getStoreList('first');
      this.loading = false;
    } else {
      this.storeId = Number(this.$route.params.storeId);
      this.productId = this.$route.params.productId;
      this.pageType = 'Edit';
      this.getStoreList();
      this.vendorList(true);
      this.productCategoryList(true);
      this.productTagList(true);
      this.chosedStore(this.storeId);
    }
  },
  methods: {
    getStoreList(str) {
      // 获取店铺列表
      authorizedList({
        storeType: 'WOOCOMMERCE'
      }).then(res => {
        this.storeList = res.data;
        if (str === 'first' && res.data.length > 0) {
          this.storeId = res.data[0].id;
        }
      });
    },
    chosedStore(storeId) {
      productVariantList({ storeId }).then(res => {
        // 规格
        var arr = [];
        res.data.forEach((ele, i) => {
          arr[i] = ele.name;
          arr[i]['value'] = ele.name.name;
          arr[i]['listLeaf'] = ele.values;
        });
        this.specList = arr;
        var allListLeaf = [];
        this.specList.forEach(item => {
          allListLeaf = allListLeaf.concat(item.listLeaf);
        });
        this.allListLeaf = allListLeaf;
        if (this.productId) {
          this.productRead();
        }
      });
    },
    productRead() {
      productWoocRead(this.productId).then(res => {
        const data = JSON.parse(JSON.stringify(res.data));
        // 价格/100
        if (data.product.type === 1) {
          data.inventories.forEach(item => {
            item.salePrice /= 100;
            item.regularPrice /= 100;
          });
        }
        data.product.regularPrice /= 100;
        data.product.salePrice /= 100;
        this.formData = data.product;

        this.defaultMsg = data.content.description;

        this.$set(
          this.formData,
          'productCategoryIds',
          data.product.categoryIds.split(',').map(item => Number(item))
        );
        this.$set(
          this.formData,
          'productTagIds',
          data.product.tagIds.split(',').map(item => Number(item))
        );
        this.$set(this.formData, 'specificationData', data.inventories);
        this.images = data.images || [];
        this.$set(this.formData, 'rules', this.rules);
        if (data.product.type === 1) {
          this.cloneSpecificationData = JSON.parse(
            JSON.stringify(data.inventories)
          );
          var idStr = '';
          data.inventories.forEach((item, index) => {
            idStr += item.titleIds + ',';
          });
          // 解析转换 规格信息 数据
          var newArr = [];
          data.variants.forEach(item => {
            var obj = {};
            obj['parent'] = item.name;
            obj['son'] = [];
            var objSon = [];
            var children = this.specList.find(ele => ele.id === item.id)
              .listLeaf;
            for (var a = 0; a < children.length; a++) {
              if (idStr.split(',').includes(String(children[a].id))) {
                objSon.push(children[a].name);
              }
            }
            obj['son'] = objSon;
            newArr.push(obj);
          });
          this.specifications = newArr;
        } else if (data.product.type === 0) {
          this.formData['productVariantIds'] = [];
        }
        this.loading = false;
      });
    },
    resetVariantList(val) {
      if (!val) return;
      productVariantList({ storeId: this.storeId }).then(res => {
        // 规格
        var arr = [];
        res.data.forEach((ele, i) => {
          arr[i] = ele.name;
          arr[i]['value'] = ele.name.name;
          arr[i]['listLeaf'] = ele.values;
        });
        this.specList = arr;
        var allListLeaf = [];
        this.specList.forEach(item => {
          allListLeaf = allListLeaf.concat(item.listLeaf);
        });
        this.allListLeaf = allListLeaf;
      });
    },
    variantNameChange(i) {
      this.specifications[i].son = [];
    },
    productCategoryList(val) {
      // 获取分类
      if (val) {
        productCategoryList({ storeId: this.storeId, parentId: -1 }).then(
          res => {
            const arr = [];
            res.data.forEach((item, index) => {
              arr[index] = item.first;
              arr[index]['seconds'] = item.seconds;
            });
            this.categoryOptions = arr;
          }
        );
      }
    },
    categoryChange(val) {
      // 添加分类
      const value = val[val.length - 1];
      if (typeof value === 'string') {
        const params = {
          isLeaf: 0,
          parentId: 0,
          name: value,
          storeId: this.storeId
        };
        productCategoryAdd(params).then(res => {
          if (res.code === 200) {
            this.$message.success(res.message);
            productCategoryList({ storeId: this.storeId, parentId: -1 }).then(
              res => {
                if (res.code === 200) {
                  const arr = [];
                  res.data.forEach((item, index) => {
                    arr[index] = item.first;
                    arr[index]['seconds'] = item.seconds;
                  });
                  this.categoryOptions = arr;
                  const id = res.data.filter(item => item.name === value)[0].id;
                  this.formData.productCategoryIds[
                    this.formData.productCategoryIds.length - 1
                  ] = id;
                }
              }
            );
          } else {
            this.formData.productCategoryIds.splice(val.length - 1, 1);
          }
        });
      }
    },
    productTagList(val) {
      // 标签列表
      if (val) {
        productTagList(this.storeId).then(res => {
          this.tagOptions = res.data;
        });
      }
    },
    productTagAdd(val) {
      // 添加标签
      const value = val[val.length - 1];
      if (typeof value === 'string') {
        const params = {
          isLeaf: 0,
          parentId: 0,
          name: value,
          storeId: this.storeId
        };
        productTagAdd(params).then(res => {
          if (res.code === 200) {
            productTagList(this.storeId).then(res => {
              if (res.code === 200) {
                this.tagOptions = res.data;
                const id = res.data.filter(item => item.name === value)[0].id;
                this.formData.productTagIds[
                  this.formData.productTagIds.length - 1
                ] = id;
              }
            });
          } else {
            this.formData.productTagIds.splice(val.length - 1, 1);
          }
        });
      }
    },
    getClick(e, str) {
      if (e.target.tagName === 'SPAN' && e.target.className === '') {
        switch (str) {
          case 'vendor':
            this.viewVendor = true;
            break;
          case 'tag':
            this.viewTags = true;
            break;
          case 'category':
            this.viewCategory = true;
            break;
        }
      }
    },
    vendorList(val) {
      if (val) {
        vendorList().then(res => {
          this.vendorOptions = res.data;
        });
      }
    },
    vendorAdd(val) {
      // 添加标签
      if (typeof val === 'string') {
        const params = {
          name: val,
          storeId: this.storeId
        };
        vendorAdd(params).then(res => {
          if (res.code !== 200) {
            this.formData.vendorId = '';
          } else {
            this.vendorList(true);
          }
        });
      }
    },
    productWoocAdd(params) {
      // 添加商品
      productWoocAdd(params).then(res => {
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$router.go(-1);
        }
      });
    },
    productWoocEdit(params) {
      productWoocEdit(params).then(res => {
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$router.go(-1);
        }
      });
    },
    submitData() {
      this.$refs['productForm'].validate(valid => {
        if (valid) {
          // 校验商品缩略图
          if (this.images.length === 0) {
            const offsetTop = document.getElementById('Images').offsetTop;
            document.documentElement.scrollTop = offsetTop - 90;
            this.$message.warning('Please Add/Select the images');
            return;
          }
          const params = JSON.parse(JSON.stringify(this.formData));
          params['storeId'] = this.storeId;
          params['inventories'] = JSON.parse(
            JSON.stringify(this.formData.specificationData)
          );
          params.content = {};
          params.content['description'] = this.$refs.ue.getUEContent();
          // 校验商品描述
          if (params.content['description'] === '') {
            const offsetTop = document.getElementById('Description').offsetTop;
            document.documentElement.scrollTop = offsetTop - 90;
            this.$message.warning('Please fill in the description');
            return;
          }
          params['productImageIds'] = this.images.map(item => item.id);
          params['productCategoryIds'] = flatten(params['productCategoryIds']);
          if (typeof params.vendorId === 'string') {
            // 提交数据时供应商为新加的时，匹配下对应id
            params.vendorId = this.vendorOptions.filter(
              item => item.name === params.vendorId
            )[0].id;
          }
          // 价格*100
          if (params.type === 1) {
            if (params.inventories.length === 0) {
              return this.$message.warning('Please add variant information');
            }
            let haveEmpty = false;
            params.inventories.forEach(item => {
              if (item.thumbnailUri === '') {
                haveEmpty = true;
                return;
              }
              item.salePrice = Math.round(item.salePrice * 100);
              item.regularPrice = Math.round(item.regularPrice * 100);
              item.quantity *= 1;
            });
            if (haveEmpty) {
              return this.$message.warning(
                'Please upload pictures of variations'
              );
            }
          }
          params.regularPrice = Math.round(params.regularPrice * 100);
          params.salePrice = Math.round(params.salePrice * 100);
          params.inventoryQuantity *= 1;
          if (this.pageType === 'Add') {
            this.inventoryStatus =
              this.isManageInventory === 1 ? 0 : this.inventoryStatus;
            this.productWoocAdd(params);
          } else if (this.pageType === 'Edit') {
            params.productGroupIds = [];
            this.productWoocEdit(params);
          }
        } else {
          this.$message.warning('Please complete the information');
          return false;
        }
      });
    },
    changeVariantSku(val) {
      changeVariantSku(val, this);
    },
    toggleCheck(val, label) {
      // 取消勾选表单复选框，清空对应数据
      toggleCheck(val, label, this);
    },
    specToggleCheck(val, label, index) {
      // 取消勾选变种内表单复选框，清空对应数据
      if (val === 0) {
        if (label === 'isManage') {
          this.formData.specificationData[index]['quantity'] = 0;
          this.formData.specificationData[index]['allowBackorders'] = 0;
          this.formData.specificationData[index]['lowInventoryThreshold'] = 0;
        } else if (label === 'allowBackorders') {
          this.formData.specificationData[index]['lowInventoryThreshold'] = 0;
        }
      } else {
        if (label === 'isVirtual') {
          delete this.formData.specificationData[index]['weight'];
          delete this.formData.specificationData[index]['length'];
          delete this.formData.specificationData[index]['width'];
          delete this.formData.specificationData[index]['height'];
        }
      }
    },
    setTagList(data) {
      this.tagOptions = data;
    },
    closeTagsDialog() {
      this.viewTags = false;
    },
    getSelectedTag(data) {
      this.viewTags = false;
      this.formData.productTagIds = data;
    },
    setCategoryList(data) {
      this.categoryOptions = data;
    },
    closeCategoryDialog() {
      this.viewCategory = false;
    },
    getSelectedCategory(data) {
      this.viewCategory = false;
      this.formData.productCategoryIds = data;
    },
    setVendorList(data) {
      this.vendorOptions = data;
    },
    closeVendorDialog() {
      this.viewVendor = false;
    },
    getSelectedVendor(data) {
      this.viewVendor = false;
      this.$set(this.formData, 'vendorId', data);
    },
    closeVariantDialog() {
      // 关闭变种弹窗
      this.viewVariant = false;
    },
    showVariantImgDialog(index, id, uri) {
      this.variantIndex = index;
      this.selectedId = id;
      this.selectedUri = uri;
      this.variantDialogVisible = true;
    },
    emitClose(data) {
      if (data[1] !== undefined) {
        if (data[0] !== this.selectedId) {
          this.formData.specificationData[this.variantIndex].thumbnailUri =
            data[1];
          this.formData.specificationData[this.variantIndex].imageId = data[0];
        }
      }
      this.variantDialogVisible = false;
    },
    choseThumbnail(data) {
      // 关闭图片缩略图弹窗
      this.thumbnailShow = false;
      if (data && data.constructor === Array) {
        this.images = data;
      }
    },
    removeItem(index) {
      this.specifications.splice(index, 1);
    },
    batchData() {
      this.batchRows = this.formData.specificationData;
      this.batchVisible = true;
    },
    closeBatch(data) {
      this.batchVisible = false;
      if (data) {
        this.formData.specificationData.forEach(item => {
          this.$set(item, this.writeLabel, data);
        });
      }
    },
    setInputVal(label) {
      // 批量设置变种信息
      if (this.formData.specificationData.length === 0) {
        return this.$message.warning('Please add the variant first');
      }
      this.writeLabel = label;
      this.batchVisible = true;
    },
    batchCheckChange(val, label) {
      // 批量设置变种信息内复选框
      if (this.formData.specificationData.length === 0) {
        return this.$message.warning('Please add the variant first');
      }
      this.formData.specificationData.forEach(item => {
        item[label] = val;
        if (label === 'isVirtual' && val === 1) {
          delete item['weight'];
          delete item['length'];
          delete item['width'];
          delete item['height'];
        } else if (label === 'isManage' && val === 0) {
          item['lowInventoryThreshold'] = 0;
          delete item['quantity'];
          delete item['lowInventoryThreshold'];
        } else if (label === 'allowBackorders' && val === 0) {
          delete ['lowInventoryThreshold'];
        }
      });
    },
    deleteSkuItem(item, index) {
      // 删除变种信息
      this.formData.specificationData.splice(index, 1);
    },
    addSpecificationItem() {
      // 添加规格信息
      this.specifications.push({
        parent: '',
        son: []
      });
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    goBack() {
      this.$router.go(-1);
    }
  }
};
